package com.arron.juc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class AtomicReferenceFieldUpdaterDemo {

    public static final AtomicReferenceFieldUpdater<MyCar,Integer> updater = AtomicReferenceFieldUpdater.newUpdater(MyCar.class,Integer.class,"a");
    public static void main(String[] args) {

        MyCar myCar = new MyCar();

        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {

            new Thread(()->{
                while (updater.compareAndSet(myCar,0,1)){

                    System.out.println(updater.get(myCar));

                }
                countDownLatch.countDown();
            },"A").start();

        }

        //主线程等待上面10个线程执行结束
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }




}


class MyCar{
    //必须使用 public volatile修饰
    public volatile Integer a=0;
}
